<?php

namespace api\components;

use yii\base\InvalidConfigException;
use yiike\wechat\models\Fans;
use yiike\wechat\models\Wechat;

/**
 * Site controller
 */
class WechatController extends Controller {

    /**
     * 微信请求的消息内容
     * @var array
     */
    public $message;

    /**
     * 微信请求关闭CSRF验证
     * @var bool
     */
    public $enableCsrfValidation = false;

    /**
     * @var Wechat;
     */
    private $_wechat;

    /**
     * 设置公众号
     * @param Wechat $wechat
     */
    public function setWechat(Wechat $wechat) {
        $this->_wechat = $wechat;
    }

    /**
     * @return mixed
     * @throws InvalidConfigException
     */
    public function getWechat() {
        if ($this->_wechat === null) {
            throw new InvalidConfigException('The "wechat" property must be set.');
        }
        return $this->_wechat;
    }

    /**
     * @var \yiike\wechat\models\Fans
     */
    private $_fans = false;

    /**
     * @var \yiike\user
     */
    private $_user = false;

    /**
     * 获取触发微信请求的微信用户信息
     * @return Fans
     */
    public function getFans() {
        if ($this->_fans === false) {
            $this->_fans = Fans::findByOpenId($this->message['FromUserName']);
        }
        $wechat = $this->getWechat();
        if (!$this->_fans) { // 存储粉丝信息
            $this->_fans = Yii::createObject(Fans::className());
            $this->_fans->setAttributes([
                'wid'     => $wechat->id,
                'open_id' => $this->message['FromUserName'],
                'status'  => Fans::STATUS_SUBSCRIBED
            ]);
            if ($this->_fans->save() && $wechat->status > Wechat::TYPE_SUBSCRIBE) { // 更新用户详细数据, 普通订阅号无权限获取
                $this->_fans->updateUser();
            }
        }
        elseif ($this->_fans->status != Fans::STATUS_SUBSCRIBED) { // 更新关注状态
            $this->_fans->subscribe();
        }
        return $this->_fans;
    }

    public function getUser() {
        if ($this->_user === false) {
            $user = $this->getFans()->user;
            if ($user) {
                $this->_user = $user;
            }
        }        
        return $this->_user;
    }


    /**
     * 响应文本消息
     * 例: $this->replyText('hello world');
     * @param $content
     * @return array
     */
    public function replyText($content) {
        return [
            'MsgType' => 'text',
            'Content' => $content
        ];
    }

    /**
     * 响应图文消息
     * 例: $this->replyNews([
     *     [
     *         'title' => 'test title',
     *         'description' => 'test description',
     *         'picUrl' => 'pic url',
     *         'url' => 'link'
     *     ],
     *      ...
     * ]);
     * @param array $articles
     * @return array
     */
    public function replyNews(array $articles) {
        if (isset($articles['title'])) {
            $articles = [$articles];
        }
        $reply = [
            'MsgType'      => 'news',
            'ArticleCount' => count($articles),
        ];
        foreach ($articles as $article) {
            $reply['Articles'][] = [
                'Title'       => $article['title'],
                'Description' => $article['description'],
                'PicUrl'      => $article['picUrl'],
                'Url'         => $article['url']
            ];
        }
        return $reply;
    }

    /**
     * 响应图片消息
     * @param $mid 图片mid(需先上传图片给wechat服务器获得mid)
     * 例: $this->replyImage([
     *     'mid' => '123456'
     * ])
     * @return array
     */
    public function replyImage($mid) {
        return [
            'MsgType' => 'image',
            'Image'   => [
                'MediaId' => $mid
            ]
        ];
    }

    /**
     * 响应语音消息
     * @param $mid 语音mid(需先上传语音给wechat服务器获得mid)
     * 例: $this->replyVoice([
     *     'mid' => '123456'
     * ])
     * @return array
     */
    public function replyVoice($mid) {
        return [
            'MsgType' => 'voice',
            'Image'   => [
                'MediaId' => $mid
            ]
        ];
    }

    /**
     * 响应视频消息
     * 例: $this->replyVideo([
     *     'mid' => '123456',
     *     'thumbMid' => '1234567'
     * ])
     * @param array $video mid(需先上传视频给wechat服务器获得mid和thumbMid)
     * @return array
     */
    public function replyVideo(array $video) {
        return [
            'MsgType' => 'video',
            'Video'   => [
                'MediaId'      => $video['mid'],
                'ThumbMediaId' => $video['thumbMid']
            ]
        ];
    }

    /**
     * 响应音乐消息
     * 例: $this->replyMusic([
     *     'title' => 'music title',
     *     'description' => 'music description',
     *     'musicUrl' => 'music link',
     *     'hgMusicUrl' => 'HQ music link', // 选填,
     *     'thumbMid' = '123456'
     * ])
     * @param array $music
     * @return array
     */
    public function replyMusic(array $music) {
        return [
            'MsgType' => 'music',
            'Image'   => [
                'Title'        => $music['title'],
                'Description'  => $music['description'],
                'MusicUrl'     => $music['musicUrl'],
                'HQMusicUrl'   => isset($music['hqMusicUrl']) ? $music['hqMusicUrl'] : $music['musicUrl'],
                'ThumbMediaId' => $music['thumbMid']
            ]
        ];
    }

}
